CREATE PROCEDURE sp_ThemChiTietPhieuThuePhong
	@MaPT int,
	@MaKT int
AS
BEGIN TRAN
	if not exists(SELECT * FROM PHIEUTHUEPHONG WHERE MaPT = @MaPT)
	begin
		raiserror('Khong ton tai phieu thue phong',16,1)
		rollback
		return
	end

	if not exists(SELECT * FROM KHACHTHUEPHONG WHERE MaKT = @MaKT)
	begin
		raiserror('Khong ton tai khach thue phong',16,1)
		rollback
		return
	end

	declare @Ma int
	set @Ma = 1

	while exists (SELECT * FROM CT_PHIEUTHUEPHONG WHERE MaCTPT = @Ma)
		set @Ma = @Ma + 1
	INSERT INTO CT_PHIEUTHUEPHONG VALUES(@Ma, @MaPT, @MaKT)
	if(@@error <> 0)
		raiserror('Loi khi them CTPT',16,1)
COMMIT